﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using DBMan.Common.Global;
using DBMan.Common.Helper;
using DBMan.Common.Helper.Mqtt;
using DBMan.Common.Helper.Udp;

namespace DBMan
{
    public partial class Deal
    {
        /// <summary>
        /// 是否启用Mqtt数据推送
        /// </summary>
        private bool IsMqttPublish = false;

        private MQTTHelper mQTTHelper = null;

        /// <summary>
        ///  (第三)构造方法
        /// </summary>
        private void DealConstructMethod2()
        {
            try
            {
                this.IsMqttPublish = (Configs.GetAndAdd("IsMqttPublish", "False").Trim().ToLower() == "true");
                this.MqttStart();
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"DBMan.Deal DealConstructMethod2 Err:{ex.Message}");
            }
        }

        private void MqttStart()
        {
            try
            {
                if (!this.IsMqttPublish)
                {
                    return;
                }
                if (this.mQTTHelper != null)
                {
                    return;
                }
                mQTTHelper = MQTTHelper.Instance;
                var objDefaultConfig = new
                {
                    serverAddr = "121.136.140.57",
                    iPort = 1883,
                    user = "w.f",
                    pwd = "123"
                };
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(objDefaultConfig);
                var jsonTag = "'";
                json = json.Replace("\"", jsonTag);
                json = Configs.GetAndAdd("MqttConnectStr", json);
                json = json.Replace(jsonTag, "\"");
                var cfg = Tool.ToDynamicsByJson(json).Select(p => new
                {
                    serverAddr = p.Get<string>("serverAddr"),
                    iPort = p.Get<int>("iPort"),
                    user = p.Get<string>("user"),
                    pwd = p.Get<string>("pwd")
                }).First();
                mQTTHelper.Connect(cfg.serverAddr, cfg.iPort, cfg.user, cfg.pwd);
                mQTTHelper.MQTTConnectedEvent += ((s, e) =>
                {
                    try
                    {
                        var sLog = $"\r\nMqtt连接成功!\r\n{Tool.ConvertJsonString(json)}\r\n";
                        Console.WriteLine(sLog);
                        //mQTTHelper.Publish("a/b/c", $"KndWuFeng:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
                        LogWrite.TxtExport_DateNow(LOG_TRACE_FILE, sLog);

                        this.TestMqttSubscribe();
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine($"MQTTConnectedEvent Err:{ex.Message}");
                        LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MQTTConnectedEvent Err:{ex.Message}");
                    }
                });
                mQTTHelper.MQTTReConnectedFailEvent += ((s, e) =>
                {
                    try
                    {
                        //Console.WriteLine("Mqtt重连失败!");
                        var sLog = $"\r\nMqtt重连失败!\r\n{Tool.ConvertJsonString(json)}\r\n";
                        Console.WriteLine(sLog);
                        LogWrite.TxtExport_DateNow(LOG_TRACE_FILE, sLog);
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine($"MQTTReConnectedFailEvent Err:{ex.Message}");
                        LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MQTTReConnectedFailEvent Err:{ex.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MqttDataPublishDeal MqttStart Err:{ex.Message}");
            }
        }

        private void MqttPublish(string _json)
        {
            try
            {
                if (!this.IsMqttPublish)
                {
                    return;
                }
                var sTopic = "DBManSyncOperDataDataPublish";
                Thread th = new Thread((ob) =>
                {
                    try
                    {
                        var json = (string)ob;
                        //UdpHelper.Send(/*"[[D:]]\r\n" +*/json);
                        if (this.mQTTHelper != null)
                        {
                            try
                            {
                                this.mQTTHelper.Publish(sTopic, json);
                            }
                            catch (Exception ex)
                            {
                                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MqttDataPublishDeal MqttPublish 1Err:{ex.Message}");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MqttDataPublishDeal MqttPublish 0Err:{ex.Message}");
                    }
                });
                th.Start(_json);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MqttDataPublishDeal MqttPublish Err:{ex.Message}");
            }
        }

        private void TestMqttSubscribe()
        {
            try
            {
                this.mQTTHelper.Subscribe("DBManSyncOperDataDataPublish");//注:临时测试的订阅
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow(LOG_ERR_FILE, $"MqttDataPublishDeal TestMqttSubscribe Err:{ex.Message}");
            }
        }

    }
}
